
<!-- <script type="text/javascript" src="/static/fmap_SDK_v2.7.0_Standalone/fengmap.min.js"></script> -->

<style> 
#showtml{ position:absolute; left:30px; top:80px; background:#FFFFFF; width:100px;}
#list_show{ position:absolute; left:30px; top:80px; background:#FFFFFF; width:120px;}
#time_tool { position:absolute; left:10px; top:10px; background:#FFFFFF; width:100%;}
.slidearea {
    padding: 10px 0;
}

.slidearea .slider {
    display: inline-block;
    position: absolute;
    width: 12px;
    height: 12px;
    top: -3px;
    left: 2px;
    border-radius: 50%;
    box-shadow: 0px 0px 1px 1px #808080;
    background-color: #fff;
}

.slidearea .layui-progress-bar {
    -moz-transition: all 0s;
    -o-transition: all 0s;
    -webkit-transition: all 0s;
    transition: all 0s;
}
.BMap_cpyCtrl {
display:none !important;
}
.anchorBL{
display:none !important;
}
</style> 
<div id="map_box" style="height: 100%;width: 100%"></div>
<div id="time_tool" style="color:white;background-color:rgba(320,138,138,0)">
  <form class="layui-form layui-form-pane " action="" id="trail_query_form" lay-filter="trail_query_form">
    <div class="layui-form-item" style="color:black">
      <div class="layui-inline">
        <div class="layui-input-inline">
          <input id="s_time" type="text" name="s_time" lay-verify="required"  placeholder="开始时间" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <div class="layui-input-inline">
          <input id="e_time" type="text" name="e_time" lay-verify="required"  placeholder="结束时间" autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-inline">
        <div class="layui-input-inline" style="width: 150px">
          <select name="trail_filter" placeholder="轨迹类型" class="layui-input">
            <option value="original_trail">原始轨迹</option>
            <option value="navi_trail">导航轨迹</option>
          </select>
        </div>
      </div>
      <div class="layui-inline">
        <div class="layui-input-inline" style="width: 150px">
          <select id="tml_list" name="device_id"  lay-verify="required" lay-search="" class="layui-input" placeholder="" >
          </select>
        </div>
        <div class="layui-form-mid layui-word-aux">—</div>
        <a class="layui-btn" lay-submit="" lay-filter="trail_query"><i class="layui-icon layui-icon-search" style="font-size: 12px"></i></a>
        <a class="layui-btn" id="run"><i class="fa fa-play" style="font-size: 12px"></i></a>
        <a class="layui-btn" id="pause"><i class="fa fa-pause" style="font-size: 12px"></i></a>
        <a class="layui-btn" id="stop"><i class="fa fa-stop" style="font-size: 12px"></i></a>
        <a class="layui-btn" id="add_play_speed"><i class="layui-icon layui-icon-next" style="font-size: 12px"></i></a>
        <a class="layui-btn" id="prev_play_speed"><i class="layui-icon layui-icon-prev" style="font-size: 12px"></i></a>
      </div>
      <div class="layui-inline" >
        <div class="layui-input-inline" style="font-size: 12px;width: 60px">
          <select class="layui-select" id="play_speed" name="play_speed">
          <option value="900">0X</option>
          <option value="800">1X</option>
          <option value="700">2X</option>
          <option value="600">3X</option>
          <option value="500">4X</option>
          <option value="400" selected="">5X</option>
          <option value="300">6X</option>
          <option value="200">7X</option>
          <option value="100">8X</option>
          <option value="0">9X</option>
        </select>
        </div>
      </div>
      <div class="layui-inline">
        <div class="layui-input-inline slidearea">
          <div class="layui-progress" lay-showpercent="true" lay-filter="trail_progress">
            <div class="layui-progress-bar layui-bg-blue" lay-percent="0%" ><font id="play_pro"  style="color:black"></font></div>
            <span class="slider"></span>
          </div>
        </div>
      </div>
      <div class="layui-inline">
        <label class="layui-form-label layui-bg-green" style="font-size: 12px;width: 60px">详情</label>
        <div class="layui-input-inline">
          <input type="checkbox" lay-skin="switch" lay-text="ON|OFF" checked name="detail_info_show">
        </div>
      </div>
    </div>
  </form>
</div>

<!-- <script type="text/javascript" src="/static/js/fmap_map.js"></script> -->
<script type="text/javascript">

form.render()
 //地图长宽设置
var body_height=$('.layui-body').height()
var body_width=$('.layui-body').width()
var map_height=body_height-60*body_height/827
var map_width=body_width
// $('#map_box').attr('style','width:'+body_width+'px;height:'+body_height+'px;')

// ----打开fmap地图start---- //


var fn_map
var open_fmap=function(div_id,map_detail){
  var content=map_detail.content
  var file=content.split('.')[0]
  fn_map = new fengmap.FMMap({
    //渲染dom
    container: document.getElementById(div_id),
    //地图数据位置
    mapServerURL: '/static/map_data/',
    defaultMapScaleLevel: 19,
    //开发者申请应用下web服务的key
    key: '9ba50831cbdde4f07c79740dae2959ff',
    //开发者申请应用名称
    appName: 'map测试',
   });
  fn_map.openMapById(file);
    // 地图记载完成事件
  fn_map.on('loadComplete', function () {
    searchAnalyser = new fengmap.FMSearchAnalyser(fn_map)
  })
}


if(map_data.length!=0){
  open_fmap('map_box',current_map)
}else{
  layer.msg('无地图')
}



// ----打开fmap地图end---- //

//给后台传时间和终端ID，获取轨迹数据

// 轨迹数据全局变量
var tarckpoint=new Array();
var trackinfo=new Array();
var line_layer;
var image_layer;
var trail_kind
// 轨迹播放的实时参数，播放速度，百分比等
var trail_opt={};
trail_opt['play_speed']=parseInt($('#play_speed').val())

form.on('submit(trail_query)',function(obj){

  var trail_param=obj.field
  trail_kind=trail_param.trail_filter
  trail_param.map_kind='fmap'
  
  if(obj.field.device_id!=='' && obj.field.detail_info_show=='on'){
      $('.layui-body').attr('style','padding:0px;bottom:160px;left:0')
      $('.layui-footer').attr('style','height:160px;left:0')
      $('.layui-footer').show()
      // $('.layui-side').hide()
      var dev=get_detail_from_id(device,obj.field.device_id)
      add_dev_detail(dev)
  }else{
    $('.layui-body').attr('style','padding:0px;bottom:0px;left:0')
    $('.layui-footer').empty()
    $('.layui-footer').hide()
  }

  trail_param=JSON.stringify(trail_param)
  //console.log(trail_param)
   $.ajax({
          type: 'POST',
          url:"/trail/?what="+'get_trail',
          data:{trail_param},
          async:true,
          dataType: 'json',
          success: function(result) {
            //console.log(result)
            interact_table(result)
            tarckpoint=new Array();
            trackinfo=new Array();
            if(result.length==0){
              layer.msg('该时间段没有轨迹数据');
              return false;
            };
            // 清除之前的覆盖物
            if(navi){
              navi.clearAll()
            }
            if(line_layer){
              trail_opt['status']='stop'
              fn_map.clearLineMark()
              image_layer.removeAll();
            }
            // if(move_marker!=null){
            //   fn_map.removeLocationMarker(move_marker)
            //   move_marker=null

            // }

            // 封装轨迹点
            trail_opt['point_order']={}
            for(var i=0;i<result.length;i++){
              var point_len=result.length
              var point_order=(Math.round((1/point_len)*100*i))+'%'
              var lng=parseFloat(result[i]['lng'])
              var lat=parseFloat(result[i]['lat'])
              
              var pt_trail = {'x':lng,'y':lat,'z':1,'groupID':1}
              pt_trail['html']='<div>'+result[i]['serv_receive']+','+result[i]['speed']+'公里/小时</div>'
              pt_trail['dev_datail']=result[i]
              trail_opt['point_order'][point_order]=pt_trail
              tarckpoint.push(pt_trail);
              trackinfo.push(result[i]);
            };

          //console.log(trail_kind)
          if(trail_kind=='original_trail'){
            setTimeout(function(){
              drawLines(tarckpoint);
              addMarkers(tarckpoint[tarckpoint.length-1], '/static/img/end.png',{'device_id':'end'});
              addMarkers(tarckpoint[0], '/static/img/start.png',{'device_id':'start'});
            },100);
          }else if(trail_kind=='navi_trail'){
            createrNavi(tarckpoint)
          } 
      }
    })
  });


//轨迹播放
let move_marker=null//该变量在本页面作为全局表里，参与了回调之后，变成了整个系统的全局变量，而且无法操作处理，似乎陷入了死循环,改var为let，赋值null，解决了这个问题
var marker_list=[]
$('#run').click(function(){

  coordIndex = 1
  // if(navi){navi.stop();
  // navi.clearAll()
  // drawLines(results);}
  if(!trail_opt['status'] | trail_opt['status']=='stop'){
    coordIndex=1
    trail_opt['status']='run'
    if(move_marker){
      move_marker.setPosition({'x':tarckpoint[0].x,'y':tarckpoint[0].y,groupID:1,height:1})
    }else{
      move_marker=addlocationMarker(tarckpoint[0], '/static/show_icon/person.png');
    }
  }else if(trail_opt['status']=='pause'){
    coordIndex=trail_opt['current_pt']
    trail_opt['status']='run'
  }
  //console.log(fn_map)
  setTimeout(function() {
    if(trail_kind=='original_trail'){
      original_trail(tarckpoint,move_marker)
    }else if(trail_kind=='navi_trail'){
      navi.simulate();
    } 
  }, 200);

});

//原始轨迹播放调用
var original_trail=function (points,mark){
  
  setSlider((coordIndex/points.length), 'trail_progress');
  mark.moveTo({
    x:tarckpoint[coordIndex].x,
    y:tarckpoint[coordIndex].y,
    time:trail_opt['play_speed']/1000,
    callback:function(obj){
      // console.log(coordIndex,points.length)
      if (coordIndex == points.length-1 | trail_opt['status']!=='run') {
        // locationMarker.show=false
        if(coordIndex == points.length-1){
          trail_opt['status']='stop'
        }
        return;
      }
      coordIndex++;
      trail_opt['current_pt']=coordIndex
      original_trail(points,mark);
    }
  })
}

// 暂停
$("#pause").click(function(){
  trail_opt['status']='pause'
  //console.log(trail_opt)
});
// 停止
$("#stop").click(function(){
  trail_opt['status']='stop'
  setSlider(0,'trail_progress')
});

// 加快播放速度
$("#add_play_speed").click(function(){

  trail_opt['play_speed']=trail_opt['play_speed']+100
  if (trail_opt['play_speed']>900){
    trail_opt['play_speed']=900
  }

  form.val('trail_query_form',{'play_speed':trail_opt['play_speed'].toString()})
});
// 降低播放速度
$("#prev_play_speed").click(function(){
  trail_opt['play_speed']=trail_opt['play_speed']-100
  if (trail_opt['play_speed']<100){
    trail_opt['play_speed']=100
  }
  form.val('trail_query_form',{'play_speed':trail_opt['play_speed'].toString()})
});


//导航轨迹播放调用
// var navi_trail=function(points) {
//   navi.simulate();
//   navi.on('complete', function() {
//     //console.log(locationMarker)
//     navi.locationMarker.visible=false
//     navi.locationMarker.show=false
//     if (coordIndex == points.length-1 | trail_opt['status']!=='run') {
//       // locationMarker.show=false
//       if(coordIndex == points.length-1){
//         trail_opt['status']='stop'
//       }
//       return;
//     }
//     coordIndex++;
//     trail_opt['current_pt']=coordIndex
//     var navi_pt=[points[coordIndex-1],points[coordIndex]]
//     createrNavi(navi_pt)

//     navi_trail(points);

//   });
// }
    
//原始轨迹播放，添加起点终点图标调用
var addMarkers=function (coord,img,marker_info) {
  var group = fn_map.getFMGroup(fn_map.groupIDs[0]);
  //返回当前层中第一个imageMarkerLayer,如果没有，则自动创建
  image_layer = group.getOrCreateLayer('imageMarker');
  var im = new fengmap.FMImageMarker({
    //设置图片路径
    url: img,
    name:marker_info['device_id'],
    x:coord.x,
    y:coord.y,
    size: 42,
    callback: function() {
      // 在图片载入完成后，设置 "一直可见"
      im.alwaysShow();
    }
  });
  image_layer.addMarker(im);
};

//画轨迹线调用
var drawLines=function(points) {
  //绘制部分
  line_layer = new fengmap.FMLineMarker();
  var lineStyle = {
      //设置线的宽度
      lineWidth: 4,
      //设置线的透明度
      alpha: 0.8,
      //设置线的类型为导航线
      lineType: fengmap.FMLineType.FMARROW,
      //设置线动画,false为动画
      noAnimate: true,
    };
    var gid = 1;
    var seg = new fengmap.FMSegment();
    seg.groupId = gid;
    seg.points = points;
    line_layer.addSegment(seg);
    fn_map.drawLineMark(line_layer, lineStyle);
};

//添加移动的轨迹点调用  
var addlocationMarker=function (coord, img) {
  var lmark = new fengmap.FMLocationMarker({
    //设置定位点标注的图片
    url: img,
    x:coord.x,
    y:coord.y,
    z:1,
    groupID:1,
    //设置定位点标注的显示尺寸
    size: 32,
    callback:function(){
      lmark.alwaysShow()
    }
  });
  //添加定位点标注
  fn_map.addLocationMarker(lmark);
  //设置定位点标注的位置
  // setLocationMakerPosition(coord)
  return lmark;
};


//创建导航
var navi
var createrNavi=function (coord) {
  //console.log('createrNavi')
  //初始化导航对象
  navi = new fengmap.FMNavigation({
    map: fn_map,
    locationMarkerUrl: '/static/show_icon/person.png',
    //设置Marker尺寸
    locationMarkerSize: 32,
    speed:50,
    //设置跟随定位的默认为true
    followPosition: true,
    //设置地图是否选择，默认false
    followAngle: true,
    //导航跟随显示级别
    scaleLevel: 0,
    // 设置导航线的样式
    lineStyle: {
      // 导航线样式
      lineType: fengmap.FMLineType.FMARROW,
      // 设置线的宽度
      lineWidth: 6,
      //设置线的颜色
      // godColor: '#FF0000',
      //设置边线的颜色
      // godEdgeColor: '#920000',
    }
  });

  //添加起点
  navi.setStartPoint({
    x: coord[0].x,
    y: coord[0].y,
    groupID: coord[0].groupID,
    url: '/static/img/start.png',
    size: 42
  });

  //添加终点
  navi.setEndPoint({
    x: coord[1].x,
    y: coord[1].y,
    groupID: coord[1].groupID,
    url: '/static/img/end.png',
    size: 42
  });

  navi.locationMarker.setPosition(coord[0]);

  navi.drawNaviLine();
  var cnt = 0;
  var length = 3;

  // 添加导航事件
  // navi.on('walking', function(data) {
  //   var v = new fm.Vector3(1, 0, 0);
  //   v.applyAxisAngle(new fm.Vector3(0, 1, 0), Math.PI - navi.locationMarker.o3d_.rotation.z);
  //   var scalar = Math.sin(cnt += .6) * Math.random() * length;
  //   v.multiplyScalar(scalar);
  //   var point = {
  //     x: data.point.x + v.x,
  //     y: data.point.y + v.z,
  //     groupID: data.groupID,
  //     zOffset: 2.5
  //   };
  //   //redMarker.setPosition(point);
  // });

}

var interact_table=function(d){
  table.render({
            elem: '#trail_detail_table',
            data: d,
            id:'trail_detail_table',
            skin:'nob',
            size:'sm',
            height:'155',
            cols: [[
                {field: 'index_num',width:80, title: '序号',templet:function(d){
                  return d.LAY_INDEX
                }},
                {field: 'heart_rate',width:80, title: '心率',sort:true},
                {field: 'blood_pres',width:120, title: '血压',sort:true,templet:function(d){
                  var blood_pres='0'
                  if(d.blood_pres!='0'){
                    blood_pres=eval('('+d.blood_pres+')')
                    blood_pres='高：'+blood_pres['h_pres']+','+'低：'+blood_pres['l_pres']
                  }
                  return blood_pres
                }},
                {field: 'temp',width:80, title: '温度',sort:true},
                {field: 'step_count',width:80, title: '步数',sort:true},
                {field: 'dirct',width:80, title: '方向',sort:true},
                {field: 'speed',width:80, title: '速度',sort:true},
                {field: 'serv_receive',width:180, title: '时间',sort:true},
                {field: 'location', title: '位置',templet:function(d){
                  
                  if(d.lng==0 | d.lng=='0'){
                    return '地址为空'
                  }else{
                    return '<a id="trail'+d.id+'" class="layui-btn layui-btn-primary layui-btn-xs" onclick="show_trail_location('+d.lng+','+d.lat+',\''+d.device_id+'\','+d.id+')">'+d.lng+'，'+d.lat+'</a>'
                  }
                  return d.lng+'，'+d.lat
                }},
            ]],
            limit:10000000
            // page: false
          });

}

var add_dev_detail=function(dev){
  var rssi=dev.dynamic.rssi
  var dev_loca=dev.dynamic.location
  var user_detail=dev.user_detail;
  var dev_user_name=dev.user_name;
  var param1=user_detail.customize_title1+'：'+user_detail.customize_value1
  var param2=user_detail.customize_title2+'：'+user_detail.customize_value2
  var param3=user_detail.customize_title3+'：'+user_detail.customize_value3

      //信息窗口参数
  var opts = {
    width : 470,     // 信息窗口宽度
    height: 450,     // 信息窗口高度
    };
  var trail_window=
        '<div class="layui-row" style="height:300px";>'+
          '<div class="layui-col-md2" style="padding:2px;background-color: #F2F2F2;">'+
            '<div class="layui-card">'+
              '<div class="layui-card-body">'+
                '<table class="layui-table" lay-size="sm" lay-skin="nob" style="font-size:13px;height: 140px";>'+
                  '<tr >'+
                  '<td colspan=2><font>'+'名称： '+dev_user_name+'</font></td>'+
                  '</tr>'+
                  '<tr>'+
                  '<td colspan=2>'+'设备ID： '+dev.device_id+'</td>'+
                  '</tr>'+
                  '<tr>'+
                  '<td >'+param1+'</td>'+'<td >'+param2+'</td>'+
                  '</tr>'+
                  '<tr>'+
                  '<td >'+param3+'</td>'+
                  '</tr>'+
                  '</table>'+
              '</div>'+
            '</div>'+
          '</div>'+
          '<div class="layui-col-md10" style="padding:2px">'+
            '<table id="trail_detail_table" class="layui-table" style="padding:0px;margin:-5px" lay-filter="trail_detail_table"></table>'+
          '</div>'+
        '</div>'
  ;
  $('.layui-footer').empty()
  $('.layui-footer').append(trail_window)
};



// 监听底部信息栏点击
table.on('row(trail_detail_table)',function(obj){
  // console.log('open_infowindow')
  if(move_marker){
    open_infowindow(obj.data)
  }
})
//信息窗口
var marker_title;
var all_static_infordow={}
var open_infowindow=function(tp){
  if(all_static_infordow[move_marker.name]){
    all_static_infordow[move_marker.name].close()
  }
  var blood_pres=''
  if(tp.blood_pres!='0'){
    blood_pres=eval('('+tp.blood_pres+')')
    blood_pres=blood_pres['h_pres']+'/'+blood_pres['l_pres']
  }

  marker_title=
    "<br><div style=''>"+
      "<table class='layui-table' lay-size='sm' lay-skin='nob' style='margin:0;padding:0;border-radius:20px'>"+
        "<tr>"+
          "<td>"+
            "<i class='fa fa-heartbeat' aria-hidden='true' style='color: red;'></i>："+tp.heart_rate+"次/min"+
          "</td>"+
          "<td>"+
            "<i class='fa fa-thermometer-empty'  style='color:#FFB800'></i>："+''+"C°"+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td>"+
           " <i class='fa fa-stethoscope' aria-hidden='true' style='color: blue;'></i>："+blood_pres+
          "</td>"+
          "<td>"+
            "<i class='fa fa-blind' aria-hidden='true' style='color:#5FB878'></i>："+tp.step_count+"步"+
          "</td>"+
        "</tr>"+
        "<tr>"+
         "<td>"+
            "<i class='fa fa-compass' aria-hidden='true' style='color:#5FB878'></i>："+tp.dirct+"°"+
          "</td>"+
          "<td>"+
            "<i class='fa fa-hourglass'  style='color:#FFB800'></i>："+tp.speed+"km/h"+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td>"+
            " <i class='fa fa-map-marker' aria-hidden='true' style='color:#5FB878'></i>："+tp.track_type+
          "</td>"+
        "</tr>"+
        "<tr>"+
          "<td colspan='2'>"+
            "<i class='layui-icon layui-icon-console' aria-hidden='true' style='color:#1E9FFF'></i>："+tp.serv_receive+
          "</td>"+
        "</tr>"+
      "</table>"+
    "</div>"
  ;

  var ctlOpt = {
      //设置弹框的宽度
      width: 250,
      //设置弹框的高度px
      height: 230,
      //设置弹框的内容，文本或html页面元素
      content: marker_title,
      //关闭回调函数
      closeCallBack: function () {
          //信息窗点击关闭操作
          delete all_static_infordow[move_marker.name]
      }
  };
  //添加弹框到地图上，绑定marker
  var popMarker = new fengmap.FMPopInfoWindow(fn_map, ctlOpt, move_marker);
  all_static_infordow[move_marker.name]=popMarker 
};


//添加选择设备列表
$(function(){ 
  $('#tml_list').empty()

  $('#tml_list').append('<option value="">选择/搜索设备</option>')
  
  for (var i = device.length - 1; i >= 0; i--) {
    var user_name=device[i]['user_name'];
    var option='<option value="'+device[i].device_id+'">'+user_name+'</option>'
    if(chosed_dev.device_id==device[i].device_id){
      option='<option value="'+device[i].device_id+'" selected="">'+user_name+'</option>'
    }
    $('#tml_list').append(option)
  }
    form.render()
}); 

laydate.render({
  elem: '#s_time'
  ,type: 'datetime'
  ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
  ,btns: ['clear','now', 'confirm']
});

laydate.render({
  elem: '#e_time'
  ,type: 'datetime'
  ,value:new Date()
  ,btns: ['clear','now', 'confirm']
});


// ----进度条拖动功能开始----//
var setSlider = function (value, filter) {
  if (value > 1) value = 1;
  if (value < 0) value = 0;
  var selectFilte = '';
  if (filter)
      selectFilter = '[lay-filter="' + filter + '"]';
  //设置进度条位置
  element.progress(filter, value * 100 + '%');
  //设置滑块位置
  $('.slider').css('left', $('.layui-progress' + selectFilter).children('.layui-progress-bar')[
      0].offsetWidth - 5 + 'px');
  $('#play_pro').text(Math.round(value * 100) + '%');
  return Math.round(value * 100) + '%';
}
var move = false;
//鼠标按下
$('.slidearea').on('mousedown', function (event) {
  if (event.button === 0 && trail_opt['status']!=null) {
    move = true;
    var offsetX = event.target == $('.slider')[0] ? Number($(event.target).css('left').replace(
        'px', '')) + event.offsetX : event.offsetX;
    var value = Math.round(offsetX / $(this).width() * 100) / 100;
    $('#play_pro').text(setSlider(value, 'trail_progress'));
  }
});
// 鼠标放开
$('.slidearea').on('mouseup', function (event) {move=false})
//鼠标移动
$(".slidearea").on("mousemove", function (event) {
  event.preventDefault();
  if (move && trail_opt['status']!=null) {
    var offsetX = event.target == $('.slider')[0] ? Number($(event.target).css('left').replace(
        'px', '')) + event.offsetX : event.offsetX;

    var value = Math.round(offsetX / $(this).width() * 100) / 100;
    var percent_num=setSlider(value, 'trail_progress')

    $('#play_pro').text(percent_num);

    if(trail_opt['point_order'][percent_num]){
      var order_num=trail_opt['point_order'][percent_num]
      // move_marker.setPosition(order_num);
      move_marker.setPosition({'x':order_num.x,'y':order_num.y})
      // fn_map.panTo(order_num);
    }
  }
});
// ----进度条拖动功能结束---- //


  </script>
